package com.example.springbootbabyu.service.impl;


import com.alibaba.fastjson.JSON;
import com.example.springbootbabyu.entity.*;
import com.example.springbootbabyu.mapper.GoodsMapper;
import com.example.springbootbabyu.service.GoodsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.redisson.api.RedissonClient;
/**
 * 功能
 * 作者：梦天
 * 日期：2025/4/18 8:58
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    private final GoodsMapper goodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;


    @Override
    public Sku getStockById(String skuId) {
        Sku stock = goodsMapper.selectStockBySkuId(skuId);
        if (stock == null) {
            throw new IllegalArgumentException("商品库存不存在");
        }
        // 确保接口规范要求的null值
        stock.setOldPrice(null);
        stock.setDiscount(null);

        return stock;
    }

    @Override
    public GoodsDetail getGoodsDetail(String id) {
        // 1. 查询商品基本信息
        GoodsDetail goodsDetail = new GoodsDetail();
        GoodsDetailDTO detail = goodsMapper.selectGoodsBaseInfo(id);
        if (detail == null) {
             throw new IllegalArgumentException("商品不存在");
        }
        BeanUtils.copyProperties(detail, goodsDetail);
        // 2. 查询品牌信息
        if (detail.getBrandId() != null) {
            Brand brand = goodsMapper.selectBrandById(detail.getBrandId());
            // 设置品牌字段为null
            brand.setType(null);
            brand.setDesc(null);
            brand.setPlace(null);
            goodsDetail.setBrand(brand);
        }
//
//        // 3. 查询主图视频
//        detail.setMainVideos(goodsDetailMapper.selectMainVideos(goodsId));
//
//        // 4. 查询主图
//        detail.setMainPictures(goodsDetailMapper.selectMainPictures(goodsId));
//
//        // 5. 查询规格
        List<GoodsSpec> specs = goodsMapper.selectSpecs(id);
//        List<GoodsSpec> goodsSpecs = new ArrayList<>();

        specs.forEach(spec -> {
            List<SpecValue> values = goodsMapper.selectSpecValues(spec.getId());
            spec.setValues(values);
        });
        log.info("goodsSpecs: {}", specs);
        goodsDetail.setSpecs(specs);

        // 6. 查询SKU
        List<GoodsSku> skus = goodsMapper.selectSkus(id);
        skus.forEach(sku -> {
            List<SkuSpec> skuSpecs = goodsMapper.selectSkuSpecs(id);
            sku.setSpecs(skuSpecs);
        });
        goodsDetail.setSkus(skus);
        log.info("skus: {}", skus);
        // 7. 查询分类
        List<CategoryDTO> categories = goodsMapper.selectCategories(detail.getCategoryId());
        log.info("categories: {}", detail.getCategoryId());
        CategoryDTO parent = goodsMapper.selectParentCategory(categories.get(0).getParentId());
        categories.add(parent);
        goodsDetail.setCategories(categories);
        log.info("categories: {}", detail.getCategories());
//
//        // 8. 查询详情内容
//        GoodsDetailContent content = new GoodsDetailContent();
//        content.setPictures(goodsDetailMapper.selectDetailPictures(goodsId));
//        content.setProperties(goodsDetailMapper.selectProperties(goodsId));
//        detail.setDetails(content);
//
//        // 9. 设置固定返回null的字段
//        detail.setIsCollect(null);
//        detail.setRecommends(null);
//        detail.setUserAddresses(null);
//
//        // 10. 查询相似商品和每日热销
//        detail.setSimilarProducts(goodsDetailMapper.selectSimilarProducts(goodsId));
//        detail.setHotByDay(goodsDetailMapper.selectHotByDay());
        List<String> mainPictures = goodsMapper.selectMainPictures(id);
        goodsDetail.setMainPictures(mainPictures);
        GoodsDetailContent details = new GoodsDetailContent();
        details.setPictures(goodsMapper.selectDetailPictures(id));
        details.setProperties(goodsMapper.selectProperties(id));
        goodsDetail.setDetails(details);

        return goodsDetail;
    }

    public GoodsDetail getGoodsDetailCache(String id) {
        // 先从缓存中获取数据
        Object obj = redisTemplate.opsForValue().get("goods:" + id);
        if (obj != null) {
            log.info("从缓存中获取商品详情{}", obj);
            // 缓存中有数据，直接返回
            String json = obj.toString();
            if ("null".equals(json)){
                return null;
            }
            GoodsDetail goodsDetail = JSON.parseObject(json, GoodsDetail.class);
            return goodsDetail;
        }else {
            synchronized (this) {
                log.info("从数据库中获取商品详情");
                obj = redisTemplate.opsForValue().get("goods:" + id);
                if (obj != null) {
                    log.info("从缓存中获取商品详情{}", obj);
                    // 缓存中有数据，直接返回
                    String json = obj.toString();
                    if ("null".equals(json)) {
                        return null;
                    }
                    GoodsDetail goodsDetail = JSON.parseObject(json, GoodsDetail.class);
                    return goodsDetail;
                }
                // 缓存中没有数据，查询数据库并缓存
                GoodsDetail goodsDetail = getGoodsDetail(id);
                redisTemplate.opsForValue().set("goods:" + id, JSON.toJSONString(goodsDetail),30, TimeUnit.SECONDS);
                return goodsDetail;
            }
        }
    }


//    public GoodsDetail getGoodsDetailCache(String id) {
//        String key = "goods:" + id;
//        // 第一次查缓存
//        GoodsDetail detail = (GoodsDetail) redisTemplate.opsForValue().get(key);
//        if (detail != null) {
//            log.info("从缓存中获取商品详情");
//            return detail;
//        }
//        // 分布式锁（以Redisson为例）
//        RLock lock = redissonClient.getLock("LOCK_" + key);
//        lock.lock();
//        try {
//            // 第二次查缓存（获取锁后再次验证）
//            detail = (GoodsDetail) redisTemplate.opsForValue().get(key);
//            if (detail != null) return detail;
//            // 查询数据库
//            log.info("从数据库中获取商品详情");
//            detail = getGoodsDetail(id);
//            // 设置缓存（含防雪崩随机时间）
//            int expireSeconds = 30 + ThreadLocalRandom.current().nextInt(10);
//            redisTemplate.opsForValue().set(
//                    key,
//                    detail, // 依赖RedisTemplate的序列化器
//                    expireSeconds,
//                    TimeUnit.SECONDS
//            );
//            return detail;
//        } finally {
//            lock.unlock();
//        }
//    }

    @Override
    public List<HotGoodsVO> getHotGoods(String id, String type, Integer limit) {
        List<HotGoodsVO> hotGoods = goodsMapper.selectHotGoods(id, type, limit);
        return hotGoods;
    }

    @Override
    public List<Goods> getRelevantGoods(Integer limit) {
        return goodsMapper.selectRelevantGoods(limit);
    }

    /**
     * 通过商品名称搜索商品
     */
    @Override
    public List<GoodsDetail> getGoodsByName(String name){
        name = "%" + name + "%";
        List<GoodsDetail> goodsDetail = goodsMapper.selectGoodsByName(name);
        return goodsDetail;
    }
}
